#ifndef resource_loader_h
#define resource_loader_h

#include "image_loader.h"
#include "singleton.h"
#include "SDL.h"
#include <string>
#include <sstream>
using namespace std;

/**
  * Top-level class for resource loaders.
  */
class ResourceLoader {
  public:
    virtual void* load (const string& path) = 0;
    virtual void unload (void* resource) = 0;
};

/**
  * Loader pour les images.
  * L'image est retournée en tant que SDL_Texture.
  */
class ImageLoader: public ResourceLoader, public Singleton<ImageLoader> {
  friend class Singleton<ImageLoader>;

  public:
    inline ImageLoader ();
    inline ~ImageLoader ();

    inline virtual void* load (const string& path);
    inline virtual void unload (void* resource);
};

ImageLoader::
ImageLoader () {
  // Nothing to do.
}

ImageLoader::
~ImageLoader () {
  // Nothing to do.
}

void* ImageLoader::
load (const string& path) {
  SDL_Surface* tmpsurf = load_image(path);
  if (tmpsurf == NULL) {
    return NULL;
  }

  /**
    * Attempt to convert to display format.
    * In case of failure, return the unconverted surface (not optimal).
    */
  SDL_Surface* dispsurf = SDL_DisplayFormat(tmpsurf);
  if (dispsurf == NULL) {
    stringstream ss;
    ss << "Unable to convert surface : " << path << " to display format.";
    LOG_WARNING(ss.str());
    return tmpsurf;
  }

  SDL_FreeSurface(tmpsurf);
  return dispsurf;
}

void ImageLoader::
unload (void* resource) {
  SDL_Texture* tex = reinterpret_cast<SDL_Texture*>(resource);
  SDL_DestroyTexture(tex);
}

#endif

